<?php
/*处理程序*/
$act = empty($_REQUEST['act'])? 'default':trim($_REQUEST['act']);

if($act == 'default'){
	//$rita = new rita('rita', 18, 2);
	//$rita->hear('这很强势');	
}

elseif($act == 'ask'){
	$result = array('error'=>0, 'message'=>'', 'content'=>'');
	$words = empty($_REQUEST['words'])? '':trim($_REQUEST['words']);
	$rita = new rita('rita', 18, 2);
	$result['content'] = $rita->hear($words);
	die(json_encode($result));
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
	<script src="http://www.ecmoban.com/content/themes/ecmoban2014/js/jquery.min.js"></script>
	<title>rita</title>
</head>
<body>
<?php if($act == 'default'){ ?>
<style>
.dialog{border:1px solid #ccc; padding:10px; width:300px; font-size:12px;}
.dialog p{margin:5px 0 5px 10px;}
.dialog textarea{width:100%; border-radius: 0 0 5px 5px; height:50px;}
.dialog input{padding:5px; width:70px; border-radius:5px; background:#fff;}
.chat{width:100%; height:300px; border:1px solid #ccc; margin-bottom:5px; overflow-y:scroll; }
</style>
<div class="dialog">
	<div class="chat">

	</div>
	<form action="" method="post" name="form">
		<textarea name="words" placeholder="请输入..."></textarea>
		<input type="hidden" name="act" value="ask">
		<input type="button" name="submit" value="提交"></button>
	</form>
</div>
<script type="text/javascript">
$(document).on('click', "form input:button", function(){
	var words = $("form").find("textarea").val();
	if(words == ""){
		alert("请输入内容");
	}else{
		$(".chat").append("<p>我："+words+"</p>");
		$.ajax({
			url:location.href,
			data:{act:'ask',words:words},
			type:'POST',
			dataType:'JSON',
			success:function(data){
				if(data.content != ""){		
					$(".chat").append("<p>rita："+data.content+"</p>");
					$("form").find("textarea").val('');
				}else{
					alert("rita无法获知您要表达的意思哦，您可以尝试重新输入或者刷新页面");
				}
			}
		})
	}
})
</script>
<?php } ?>
</body>
</html>
<?php
/*类*/
class rita{
	public $name;
	public $age;
	public $gender;
	
	public function __construct($name, $age, $gender){
		$this->name = $name;
		$this->age = $age;
		$this->gender = self::gender($gender);
	}

	public function hear($words){
		//echo "u say: $words<br/>";
		$response = $this->think($words);
		return $this->say($response);
	}	
	
	public function say($response){
		//echo "rita say: $response<br/>";
		return $response;
	}

	public function think($words){
		$result = file_get_contents("http://api.qingyunke.com/api.php?key=free&appid=0&msg={$words}");
		$result = json_decode($result, true);
		return $result['content'];
	}
	
	public function eat(){
		
	}	
	
	public static function gender($gender){
		$g = "";
		switch($gender){
			case 1:
				$g = "男";
				break;
			case 2:
				$g = "女";
				break;				
			default:
				$g = "保密";
		}
		return $g;
	} 
}

?>